<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.filename" size="small" clearable placeholder="输入文件名称搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.b2b" size="small" clearable placeholder="输入B2B号搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <date-range-picker v-model="query.createTime" class="date-item" />
        <rrOperation />
      </div>
      <crudOperation :permission="permission">
        <!-- 新增 -->
        <!-- <el-button
          slot="left"
          v-permission="['admin','purchaseRequest:add']"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-upload"
          @click="crud.toAdd"
        >上传
        </el-button> -->
      </crudOperation>
      <!--表单组件-->
      <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.add ? '文件上传' : '编辑文件'" width="500px">
        <el-form ref="form" :model="form" size="small" label-width="80px">
          <el-form-item label="文件名">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <!--   上传文件   -->
          <el-form-item v-if="crud.status.add" label="上传">
            <el-upload
              ref="upload"
              :limit="1"
              :before-upload="beforeUpload"
              :auto-upload="false"
              :headers="headers"
              :on-success="handleSuccess"
              :on-error="handleError"
              :action="baseApi + '/api/purchaseRequest/upload?name=' + form.name"
            >
              <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
              <div slot="tip" class="el-upload__tip">可上传任意格式文件，且不超过100M</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button v-if="crud.status.add" :loading="loading" type="primary" @click="upload">确认</el-button>
          <el-button v-else :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!-- 表单组件
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="B2B号" prop="b2b">
            <el-input v-model="form.b2b" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="状态（0：未审核,1：已审核 2：已取消）">
            <el-input v-model="form.status" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="创建日期">
            <el-date-picker v-model="form.createTime" type="datetime" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog> -->
      <el-dialog :visible.sync="dialog" title="采购清单详情" append-to-body top="30px" width="85%">
        <el-table ref="detailTable" :data="errorInfo" size="small" style="width: 100%;">
          <el-table-column type="index" width="50"/>
          <!-- <el-table-column prop="index" label="序号" /> -->
          <!-- <el-table-column prop="b2b" label="b2b号" /> -->
          <el-table-column prop="model" label="型号" />
          <el-table-column prop="quantity" label="数量" />
          <!-- <el-table-column prop="expectedDeliveryDate" label="期望交付日" /> -->
          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="customer" label="客户" />
          <!-- <el-table-column prop="createTime" label="创建日期" /> -->
        </el-table>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column prop="filename" label="文件名称" />
        <el-table-column prop="b2b" label="B2B号" />
        <el-table-column prop="rows" label="总项次" />
        <el-table-column prop="purchaseAttribute" label="采购性质" />
        <el-table-column prop="status" label="状态" :formatter="getStatusLable">
          <!-- <template slot-scope="scope">
            {{getStatusType(scope.row.status)}}
          </template> -->
        </el-table-column>
        <el-table-column prop="createBy" label="采购确认人" />
        <el-table-column prop="createTime" label="采购确认日期" />
        <!-- <el-table-column prop="auditBy" label="审批人" />
        <el-table-column prop="auditTime" label="审批时间" /> -->
        <el-table-column label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="info(scope.row.id)">详情</el-button>
            <el-button v-if="scope.row.status == 0" v-permission="['admin','purchaseRequest:audit']" size="mini" style="margin-right: 3px;" type="text" @click="pass(scope.row.id)">审核</el-button>
            <el-button v-if="scope.row.status == 0" v-permission="['admin','purchaseRequest:audit']" style="margin-left: -2px" type="text" size="mini" @click="cancel(scope.row.id)">取消</el-button>
            <el-button style="margin-left: -2px" type="text" size="mini" @click="download(scope.row.id, scope.row.filename)">导出</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { downloadFile } from '@/utils/index'
import crudPurchaseRequest from '@/api/purchaseRequest'
import crudPurchaseRequestDetail from '@/api/purchaseRequestDetail'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
// import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import dateRangePicker from '@/components/DateRangePicker'

const defaultForm = { id: null, b2b: null, status: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'PurchaseRequest',
  components: { pagination, crudOperation, rrOperation, dateRangePicker },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '采购单申请主表', url: 'api/purchaseRequest', idField: 'id', sort: ['status,asc', 'id,desc'], crudMethod: { ...crudPurchaseRequest }})
  },
    dicts: ['aduit_status'],
  data() {
    return {
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'purchaseRequest:add'],
        edit: ['admin', 'purchaseRequest:edit'],
        del: ['admin', 'purchaseRequest:del']
      },
      rules: {
        b2b: [
          { required: true, message: 'B2B号不能为空', trigger: 'blur' }
        ]
      },
      errorInfo: '',
      dialog: false,
      loading: false
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  created() {
    this.crud.optShow = {
      add: false,
      edit: false,
      del: true,
      download: false,
      reset: true
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    indexMethod(index){
      return (index + 1) + (this.crud.page.page -1) * this.crud.page.size
    },
    getStatusLable(row, column, cellValue, index) {
      const key = row[column.property]
      // console.log(this.dict.label.aduit_status[key])
      return this.dict.label.aduit_status[key]
    },
    info(id) {
      this.dialog = true
      crudPurchaseRequestDetail.list(id).then(res => {
        this.errorInfo = res
      })
    },
    // 审核
    pass(id) {
      crudPurchaseRequest.pass(id).then(res => {
        this.crud.toQuery()
        this.crud.notify('审核成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    cancel(id) {
      crudPurchaseRequest.cancel(id).then(res => {
        this.crud.toQuery()
        this.crud.notify('取消成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    download(id, filename) {
      crudPurchaseRequestDetail.download(id).then(res => {
        this.crud.notify('导出成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        downloadFile(res, filename, 'xlsx')
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    // 上传文件
    upload() {
      this.$refs.upload.submit()
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.name = file.name
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.crud.status.add = CRUD.STATUS.NORMAL
      this.crud.resetForm()
      this.crud.toQuery()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 5000
      })
      this.loading = false
    }
  }
}
</script>

<style scoped>

</style>
